package util;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import java.io.File;
import javax.imageio.ImageIO;

public class Thumbnailer {
    String src;
    String dst;

    public Thumbnailer(String imageSrc, String imageDst)
    {
        this.src = imageSrc;
        this.dst = imageDst;
        prepareFile();

    }
    private void prepareFile(){
        try{
            BufferedImage img = ImageIO.read(new File(src));
            BufferedImage thumb = scaleImage(img, 120);
            ImageIO.write(thumb, "JPG", new File(dst));
        }catch(Exception ex){
            System.out.println("hovsa billede" + ex.getMessage());

        }
    }


     private BufferedImage scaleImage(final BufferedImage bufferedImage,
        final int size) {
        final double boundSize = size;

        final int origWidth = bufferedImage.getWidth();
        final int origHeight = bufferedImage.getHeight();

        double scale;

        if (origHeight > origWidth)
            scale = boundSize / origHeight;
        else
            scale = boundSize / origWidth;

        /*
         * Don't scale up small images.
         */
        if (scale > 1.0)
            return (null);

        final int scaledWidth = (int) (scale * origWidth);
        final int scaledHeight = (int) (scale * origHeight);

        final Image scaledImage =
            bufferedImage.getScaledInstance(scaledWidth, scaledHeight,
                Image.SCALE_SMOOTH);

        // new ImageIcon(image); // load image
        // scaledWidth = scaledImage.getWidth(null);
        // scaledHeight = scaledImage.getHeight(null);

        final BufferedImage scaledBI =
            new BufferedImage(scaledWidth, scaledHeight,
                BufferedImage.TYPE_INT_RGB);

        final Graphics2D g = scaledBI.createGraphics();

        g.drawImage(scaledImage, 0, 0, null);

        g.dispose();

        return (scaledBI);
    }
}
